package materials

import (
	"context"
	"fmt"
	"net/http"
	"strings"
	"wms/model"

	"wms/internal/svc"
	"wms/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type MaterialsListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMaterialsListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MaterialsListLogic {
	return &MaterialsListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MaterialsListLogic) MaterialsList(req *types.MaterialsListRequest) (resp *types.MaterialsListResponse, err error) {
	resp = new(types.MaterialsListResponse)

	//1.查询分页
	var query string
	var querys []string
	if len(req.Name) > 0 {
		querys = append(querys, fmt.Sprintf(`name like '%%%s%%' `, req.Name))
	}
	if len(req.Types) > 0 {
		querys = append(querys, fmt.Sprintf(`types like '%%%s%%' `, req.Types))
	}

	if len(querys) > 0 {
		query = " where " + strings.Join(querys, " and ")
	}

	queryWithLimit := query + fmt.Sprintf(" order by id desc limit %d,%d", (req.Page-1)*req.Size, req.Size)
	list, err := l.svcCtx.MaterialsModel.FindByPage(l.ctx, queryWithLimit)
	if err != nil {
		if err == model.ErrNotFound {
			resp.Code = http.StatusNoContent
			resp.Msg = "没有数据"
			return
		}

		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return
	}

	//2.计算总数
	total, err := l.svcCtx.MaterialsModel.Count(l.ctx, query)
	if err != nil {
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return
	}

	resp.Data.Total = total
	for _, materials := range list {
		resp.Data.List = append(resp.Data.List, types.Materials{
			Id:        materials.Id,
			Name:      materials.Name,
			Types:     materials.Types,
			CreatedAt: materials.CreatedAt.Unix(),
		})
	}

	resp.Code = http.StatusOK
	resp.Msg = "成功"
	return
}
